package com.way.controller;

import com.way.dto.SysUserVo;
import com.way.constants.CommonConstants;
import com.way.domain.system.SysUser;
import com.way.dto.CommonResult;
import com.way.service.LoginService;
import com.way.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@RestController
@Api(tags = "认证")
public class LoginController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private LoginService sysLoginService;

    @ApiOperation("登录")
    @PostMapping("/login")
    public CommonResult login(@RequestBody @Validated SysUserVo userParams, BindingResult bindingResult) {
        if(bindingResult.hasErrors()) {
            return CommonResult.fail(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        SysUser user = sysLoginService.login(userParams.getLoginName(), userParams.getPassword());
        return CommonResult.success(tokenService.createToken(user));
    }

    @ApiOperation("登出")
    @GetMapping("/logout")
    public CommonResult logout(HttpServletRequest request) {
        String token = request.getHeader(CommonConstants.TOKEN_KEY_STRING);
        SysUser user = tokenService.getUser(token);
        if (null != user) {
            tokenService.expireToken(user.getId());
        }
        return CommonResult.success();
    }
}
